﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using FlowBasis.Json;
using System.IO;

namespace FlowBasis.Web.Mvc
{
    
    public class PostRpcModelBinder : IModelBinder
    {
        private IModelBinder defaultModelBinder;

        public PostRpcModelBinder(IModelBinder defaultModelBinder)
        {
            this.defaultModelBinder = defaultModelBinder;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var httpContext = controllerContext.HttpContext;
            if (httpContext.Request.ContentType.StartsWith("application/json") && httpContext.Request.RequestType == "POST")            
            {
                ValueProviderResult modelValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (modelValue != null && modelValue.RawValue != null)
                {
                    var jObjectRootMapper = FlowBasis.Services.ServiceResolver.Instance.Get<FlowBasis.Json.IJObjectRootMapper>();
                    object processedValue = jObjectRootMapper.FromJObject(modelValue.RawValue, bindingContext.ModelType);
                    return processedValue;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return this.defaultModelBinder.BindModel(controllerContext, bindingContext);
            }
        }

    }
      
}
